package com.nustalk;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;

import javax.net.ssl.HttpsURLConnection;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;

import android.widget.Toast;

public class NUSTalkManager {
	private static final String LAPI_KEY = "2ZylrvIKXE7n9BsNwx5hr";
	private static final String SERVER_IP = "184.73.170.xxx";
	private static final int SERVER_PORT = 5222;
	
	private static NUSTalkManager manager = null;
	
	private ConnectionConfiguration config;
	private XMPPConnection connection;
	
	private ChatManager chatManager;
	protected MessageListener messageListener;
	
	public static NUSTalkManager getManager() {
		if (manager == null) {
			manager = new NUSTalkManager();
		}
		return manager;
	}

	public void login(String username, String password) throws InvalidLoginException, XMPPException {
		if(!validate(username, password)) {
			throw new InvalidLoginException();
		}
		
		config = new ConnectionConfiguration(SERVER_IP, SERVER_PORT);
		config.setSASLAuthenticationEnabled(false);
		config.setSecurityMode(SecurityMode.disabled);
			
		connection = new XMPPConnection(config);
		connection.connect();
		chatManager = connection.getChatManager();
		
		try {
			connection.login(username, password);
		} catch (XMPPException ex) {
			connection.disconnect();
			connection = new XMPPConnection(config);
			connection.connect();
			chatManager = connection.getChatManager();
			connection.getAccountManager().createAccount(username, password);
			connection.login(username, password);
		}
	}
	
	public void setStatus(boolean available, String status) {
		Presence.Type type = available? Presence.Type.available: Presence.Type.unavailable;
		Presence presence = new Presence(type);
		presence.setStatus(status);
		connection.sendPacket(presence);
	}
	
	public Collection<RosterEntry> getRoster() {
		return connection.getRoster().getEntries();			
	}
	
	public void addBuddy(String userID) throws XMPPException {
		String name = connection.getAccountManager().getAccountAttribute("name");
		connection.getRoster().createEntry(userID, name, null);
	}
	
	public void sendMessage(String userID, String msg) throws XMPPException {
		Chat chat = chatManager.createChat(userID, messageListener);
		chat.sendMessage(msg);
	}
	
	public void logout() {
		if (connection!=null && connection.isConnected()) {
			connection.disconnect();
		}
	}
	
	public boolean validate(String username, String password) {
		URL url = null;
		System.out.println("Test " + username);
		try {
			url = new URL(
					"https://ivle.nus.edu.sg/api/login/?"
					+ "apikey=" + LAPI_KEY
					+ "&userid=" + username
					+ "&password=" + password
					+ "&__VIEWSTATE=wEPDwULLTEzODMyMDQxNjEPZBYCAgEPZBYEAgEPD2QWAh4Gb25ibHVyBQ91c2VySWRUb1VwcGVyKClkAgkPD2QWBB4Lb25tb3VzZW92ZXIFNWRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdsb2dpbmltZzEnKS5zcmM9b2ZmaW1nLnNyYzE7Hgpvbm1vdXNlb3V0BTRkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbG9naW5pbWcxJykuc3JjPW9uaW1nLnNyYzE7ZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUJbG9naW5pbWcx");
		} catch (MalformedURLException e) {
		}
		HttpsURLConnection conn = null;
		try {
			conn = (HttpsURLConnection) url.openConnection();
			conn.setInstanceFollowRedirects(false);
			if (conn.getHeaderField("Location") != null) {
				return true;
			}
		} catch (IOException e) {
			
		}
		return false;
	}
}
